import 'dart:convert';
import 'dart:math';
import 'package:decimal/decimal.dart';
import 'package:event_bus/event_bus.dart';
import 'package:get/get.dart';

var _random = Random();
EventBus eventBus = EventBus();

extension StringKt on String? {
  bool get isNullOrEmpty {
    return this == null || this!.isEmpty;
  }

  List<String>? get toStringList {
    List<String>? list;
    try {
      var jsonMap = jsonDecode(this ?? '');
      if (jsonMap is List) {
        for (var value in jsonMap) {
          if (value is String) {
            list ??= [];
            list.add(value);
          }
        }
      }
    } catch (e) {
      e.printInfo();
    }
    return list;
  }

  String get nullSafe => this ?? '';

  String get replaceLineBreak => (this ?? '').replaceAll('\n', '');
}

extension ListKx<T> on List<T>? {
  T? get randomOrNull {
    if (this == null || this!.isEmpty) {
      return null;
    } else {
      return this![_random.nextInt(this!.length)];
    }
  }

  bool get isNullOrEmpty => this == null || this!.isEmpty;

  String? get toJsonString {
    if (this == null || this!.isEmpty) {
      return null;
    } else {
      try {
        return jsonEncode(this);
      } catch (e) {
        e.printInfo();
      }
      return null;
    }
  }
}

extension IterableKx on Iterable? {
  bool get isNullOrEmpty => this == null || this!.isEmpty;
}

String numFixed(dynamic nums, {int position = 2}) {
  double num;
  if (nums is double) {
    num = nums;
  } else {
    num = double.parse(nums.toString());
  }
  var numString = Decimal.parse(num.toString()).toString();
  if ((numString.length - numString.lastIndexOf(".") - 1) < position) {
    return (num.toStringAsFixed(position)
        .substring(0, numString.lastIndexOf(".") + position + 1)
        .toString());
  } else {
    return (numString
        .substring(0, (numString.lastIndexOf(".") + position + 1))
        .toString());
  }
}
